package com.bwie.cart.sync;


import com.bwie.cart.constants.CartConstants;

import com.bwie.cart.domain.vo.CartItem;

import com.bwie.cart.service.CartService;

import com.bwie.common.redis.service.RedisService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.scheduling.annotation.Scheduled;

import org.springframework.stereotype.Component;


import java.util.Collection;

import java.util.Map;


@Component

public class CartRedisSync {

    /**
     * 注入
     */

    @Autowired

    private RedisService redisService;

    @Autowired

    private CartService service;


    @Scheduled(cron = "0 0 0/5 * * *")

    public void CartRedisSync() {

        //获取key

        String CartKey = CartConstants.USER_CART + "*";

        //清空

        service.delAllCartItem();

        //获取到所有的key

        Collection<String> keys = redisService.keys(CartKey);

        //循环

        keys.forEach(key -> {

            //获取到所有的商品详情

            Map<String, CartItem> redisCart = redisService.getCacheMap(key);

            //循环

            redisCart.forEach((cartItemKey, cartItemValue) -> {

                //将cartItem插入到数据库

                service.syncCartItem(cartItemValue);

            });

        });

    }

}
